import Vue from 'vue';
import VueRouter from 'vue-router';
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';

import './public-path';
import App from './App.vue';
import routes from './routes';
import store from './store';
import SharedModule from '@/shared';

Vue.use(Antd);
Vue.config.productionTip = false;

let instance = null;
let router = null;

if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

/**
 * 渲染函数
 * 主应用生命周期钩子中运行/子应用单独启动时运行
 */
function render(props = {}) {
  // 当传入的 shared 为空时，使用子应用自身的 shared
  // 当传入的 shared 不为空时，主应用传入的 shared 将会重载子应用的 shared
  const { shared = SharedModule.getShared() } = props;
  SharedModule.overloadShared(shared);
  router = new VueRouter({
    base: window.__POWERED_BY_QIANKUN__ ? '/manage/' : '/',
    mode: 'history',
  });
  router.beforeEach((to, from, next) => {
    // 如果已经添加动态路由，next
    if (router.options.isAddDynamicMenuRoutes) {
      next();
    } else {
      // 获取路由表数据
      const menus = JSON.parse(localStorage.getItem('menus'));
      if (menus) {
        // 递归处理生成动态路由表
        fnAddDynamicMenuRoutes(menus.route);
        router.options.isAddDynamicMenuRoutes = true;
        next();
      } else {
        next()
      }
    }
  })
  // 挂载应用
  instance = new Vue({
    router,
    store,
    render: (h) => h(App)
  }).$mount('#app');
}

/**
 * 添加动态(菜单)路由
 * @param menuList
 * @param dynamicRoutes
 */
function fnAddDynamicMenuRoutes(menuList = [], dynamicRoutes = []) {
  let temp = []
  for (let i = 0; i < menuList.length; i++) {
    if (menuList[i].children && menuList[i].children.length >= 1) {
      temp = temp.concat(menuList[i].children)
    } else if (menuList[i].path) {
      menuList[i].path = menuList[i].path.substring(7)
      console.log(menuList[i].path, 'pathpathpathpathpath');
      let route = {
        path: menuList[i].path,
        component: null,
        name: menuList[i].path,
        meta: {
          menuId: menuList[i].id,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
        }
      }
      try {
        route['component'] = () => import(`./pages${menuList[i].path}.vue`) || null
      } catch (e) {
        console.log(e);
      }
      dynamicRoutes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, dynamicRoutes)
  } else {
    routes.push(...dynamicRoutes)
    console.log(routes, 'dynamicRoutesdynamicRoutesdynamicRoutes');
    router.addRoutes(routes)
    console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

export async function bootstrap() {
  console.log('vue app bootstraped');
}

export async function mount(props) {
  console.log('vue mount', props);
  render(props);
}

export async function unmount() {
  console.log('vue unmount');
  instance.$destroy();
  instance = null;
  router = null;
}
